package org.pointex.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.pointex.common.controller.BaseController;
import org.pointex.common.util.RedisUtil;
import org.pointex.common.util.constant.Constant;
import org.pointex.dao.impl.CreditsRuleDaoImpl;
import org.pointex.dao.impl.CreditsTypeDaoImpl;
import org.pointex.domain.CreditsRecord;
import org.pointex.domain.CreditsRule;
import org.pointex.domain.CreditsType;
import org.pointex.domain.Users;
import org.pointex.service.CreditsRecordService;
import org.pointex.service.CreditsRuleService;
import org.pointex.service.MaxNoService;
import org.pointex.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @ClassName: TaskController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author Kenny_Z' szqiuk@gmail.com
 * @date 2016年10月23日 下午9:18:39
 *
 */
@Controller
@RequestMapping("/View/task/")
public class TaskController extends BaseController {

	@Autowired
	private CreditsRuleService creditsRuleService;

	@Autowired
	private CreditsRecordService creditsRecordService;

	@Autowired
	private CreditsRuleDaoImpl creditsRuleDaoImpl;

	@Autowired
	private CreditsTypeDaoImpl creditsTypeDaoImpl;

	@Autowired
	private MaxNoService maxNoService;
	
	@Autowired
	protected RedisTemplate<String, String> redisTemplate;

	@RequestMapping("inventory")
	public ModelAndView inventory() {
		return new ModelAndView();
	}

	@RequestMapping("task")
	public ModelAndView task() {
		return new ModelAndView();
	}

	@RequestMapping("time")
	public ModelAndView time() {
		ModelAndView mav = new ModelAndView();
		int issign = 0;
		try {
			Users users = getUsersItem(request);
			Map param = new HashMap();
			param.put("userId", users.getUserId());
			param.put("creditsBehaviorId", "CB00001");
			param.put("createDt", DateUtil.formatDate_YYYYMMDD(new Date()));
			List<CreditsRecord> list = creditsRecordService
					.getUserSignRecord(param);
			if (list.size() > 0)
				issign = 1;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			mav.addObject("issign", issign);
		}
		return mav;
	}

	// 我的积分
	@RequestMapping(value = "getUserSignRecord", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void getUserCreditsRecord(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();

		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.add(Calendar.MONTH, 0);
			c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
			String first = format.format(c.getTime());
			System.out.println("===============first:" + first);

			// 获取当前月最后一天
			Calendar ca = Calendar.getInstance();
			ca.set(Calendar.DAY_OF_MONTH,
					ca.getActualMaximum(Calendar.DAY_OF_MONTH));
			String last = format.format(ca.getTime());
			System.out.println("===============first:" + last);

			Users users = getUsersItem(request);
			Map param = new HashMap();
			param.put("userId", users.getUserId());
			param.put("startTime", first);
			param.put("endTime", last);
			param.put("creditsBehaviorId", "CB00001");// 签到

			List<CreditsRecord> records = creditsRecordService
					.getUserSignRecord(param);
			jsonObject.put("item", records);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "addSign", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void addSign(HttpServletResponse response)
			throws ArithmeticException {
		JSONObject jsonObject = new JSONObject();
		int signresult = 0;// 签到失败
		try {
			Users users = getUsersItem(request);
//			Map param = new HashMap();
//			param.put("userId", users.getUserId());
//			param.put("createDt", DateUtil.formatDate_YYYYMMDD(new Date()));
//			List<CreditsRecord> list = creditsRecordService.selectParam(param);
			RedisUtil redisUtil = new RedisUtil(redisTemplate);
			Object issign=redisUtil.getMapbyKey(users.getUserId(), Constant.Redis_UserIsSign)==null?"0":redisUtil.getMapbyKey(users.getUserId(), Constant.Redis_UserIsSign);
			// 当天未签到执行签到操作时写库避免数据重复
				if(issign=="0"){
					// 获取执行该次签到的所得积分
					int credits = creditsRuleService.getCreditsByRule(users,
							"CB00001");
					//签到成功后redis缓存当天签到状态
					if (credits != 0){
						HashMap<String, Object> hashmap=new HashMap<String, Object>();
						hashmap.put(Constant.Redis_UserIsSign, "1");
						redisUtil.add_Map(hashmap, users.getUserId());
						signresult = 1;// 返回签到成功状态
					}
				}else{
					signresult = 2;// 重复签到
				}
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			jsonObject.put("signresult", signresult);
			try {
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@RequestMapping(value = "getMembrTask", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
	public void getMembrTask(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		List<Hashtable<Object, Object>> memberTask = new ArrayList<Hashtable<Object, Object>>();
		try {
			Map param = new HashMap();
			param.put("memberId", "member01");// 根据登录用户所属会员单位过滤
			param.put("status", "1");
			param.put("del_f", "0");

			List<CreditsType> ctypelist = creditsTypeDaoImpl.selectParam(param);
			for (CreditsType creditsType : ctypelist) {
				Hashtable<Object, Object> temp = new Hashtable<Object, Object>();
				temp.put("creditsTypeName", creditsType.getCreditsTypeName());
				Map ruleparam = new HashMap();
				ruleparam.put("creditsTypeId", creditsType.getCreditsTypeId());
				ruleparam.put("memberId", creditsType.getMemberId());
				ruleparam.put("startCreditsDt",
						DateUtil.formatDate_YYYYMMDDHHMMSS(new Date()));
				ruleparam.put("endCreditsDt",
						DateUtil.formatDate_YYYYMMDDHHMMSS(new Date()));
				List<CreditsRule> crulelist = creditsRuleDaoImpl
						.selectParam(ruleparam);

				for (CreditsRule creditsRule : crulelist) {
					// 根据不同的任务类型判断是否完成任务
					creditsRule.setIsfinish(0);
				}
				temp.put("crulelist", crulelist);
				memberTask.add(temp);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				jsonObject.put("Membertask", memberTask);
				feedback(response, jsonObject.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当前月第一天：
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());
		System.out.println("===============first:" + first);

		// 获取当前月最后一天
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH,
				ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());
		System.out.println("===============last:" + last);
	}

}
